import React, { useRef } from 'react';
import { apiSystemUsers } from '@/api/system/users.api';
import { ActionType, ProColumnType } from '@ant-design/pro-table';
import styles from './style.module.less';
import { history, Link } from 'umi';
import { Button, Form, Input, message, Popconfirm, Space } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import MultiList from '@/components/MultiList';
import { useRequest } from 'ahooks';
import { apiSystemPermissions, apiRole } from '@/api/system/roles.api';
import { PlusOutlined } from '@ant-design/icons';
import KPageHeader from '@/components/KPageHeader';
import KTable from '@/components/KTable';

// 添加到角色
const DialogFormAddRole = (user: API.Users) => {
  const [form] = Form.useForm();
  const { data, run: getData, loading } = useRequest(apiRole.getList, {
    manual: true,
    cacheKey: 'system.role',
  });

  const onVisibleChange = async (visible: boolean) => {
    if (visible) {
      await getData();
    }
  };
  return (
    <DrawerForm<API.Users>
      form={form}
      title={'添加到角色'}
      trigger={<a>添加到角色</a>}
      initialValues={{
        roles: [],
        ...user,
      }}
      onVisibleChange={onVisibleChange}
    >
      <Form.Item label={'用户'} name={'username'} required={true}>
        <Input readOnly={true} />
      </Form.Item>

      <Form.Item label={'添加角色'} name={'roles'} required={true}>
        <MultiList
          loading={loading}
          options={data?.items ?? []}
          onSearch={v => getData({ search: v })}
        />
      </Form.Item>
    </DrawerForm>
  );
};

// 添加权限
const DialogFormAddPermission = (user: API.Users) => {
  const { data, run: getData, loading } = useRequest(apiSystemPermissions, {
    manual: true,
    cacheKey: 'system.permissions',
  });

  const onVisibleChange = async (visible: boolean) => {
    if (visible) {
      await getData();
    }
  };

  // 表单提交
  const onFormSubmit = async (data: API.Users) => {
    console.log('u', data);
  };
  return (
    <DrawerForm<API.Users>
      title={'添加权限'}
      trigger={<a>添加权限</a>}
      initialValues={{
        ...user,
      }}
      onVisibleChange={onVisibleChange}
      onFinish={onFormSubmit}
    >
      <Form.Item label={'用户'} name={'username'} required={true}>
        <Input readOnly={true} />
      </Form.Item>

      <Form.Item label={'添加权限'} name={'roles'} required={true}>
        <MultiList
          loading={loading}
          options={
            data?.map(item => ({
              id: item.id,
              name: item.name,
              remark: item.title,
            })) ?? []
          }
          mode={1}
          columns={['权限名', '描述']}
          onSearch={v => getData({ search: v })}
        />
      </Form.Item>
    </DrawerForm>
  );
};

// 删除按钮
const DeleteButton = (props: { user: API.Users; onSuccess: () => void }) => {
  const { run } = useRequest(apiSystemUsers.delete, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      props.onSuccess();
    },
  });
  return (
    <Popconfirm
      title={'确定要删除此行数据?'}
      onConfirm={() => run([props.user.id])}
    >
      <a>删除</a>
    </Popconfirm>
  );
};

export default () => {
  const table = useRef<ActionType>();
  // 表头
  const columns: ProColumnType<API.Users>[] = [
    {
      title: '登录名/显示名',
      render: (_, record) => (
        <div className={styles.userinfo}>
          <div>
            <Link to={`/system/users/${record.id}`}>{record.username}</Link>
          </div>
          <div>{record.nickname}</div>
        </div>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '最后登录时间',
      dataIndex: 'last_login_time',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space>
          <DialogFormAddRole {...record} />
          <DialogFormAddPermission {...record} />
          <DeleteButton
            user={record}
            onSuccess={() => table.current?.reload()}
          />
        </Space>
      ),
    },
  ];

  // 创建用户
  const onClickCreate = () => {
    history.push('users/new');
  };

  return (
    <>
      <KPageHeader title={'管理员'} showBack={false} />

      <KTable
        actionRef={table}
        rowKey={'id'}
        search={false}
        request={apiSystemUsers.getList}
        columns={columns}
        toolbar={{
          title: (
            <Button
              type={'primary'}
              icon={<PlusOutlined />}
              onClick={onClickCreate}
            >
              新建管理
            </Button>
          ),
        }}
      />
    </>
  );
};
